package com.licheedev.serialtool.util;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HexSaveData2File {
    public static HexSaveData2File hexSaveData2File = null;
    private String TAG = "liuyue";
    private File fileWrite = null;
    private FileOutputStream fos = null;
    private String hubMac = null;
    private String fileDir = null;
    public static String rootLevelPath = Environment.getExternalStorageDirectory().getPath() + "/level";
    public HexSaveData2File(String hubMac) {
        this.hubMac = hubMac;
        this.fileDir = rootLevelPath;
        initFile();
    }

    public void initFile() {
        SimpleDateFormat dataformat = new SimpleDateFormat("yyyy.MM.dd_HH.mm.ss");// 设置日期格式
        SimpleDateFormat dataformatyyyyMMdd = new SimpleDateFormat("yyyy_MM_dd");// 设置日期格式
        Date nowDate = new Date();
        String dateDirName = dataformatyyyyMMdd.format(nowDate);    //获取日期字符串构建目录
        String dataNowString = dataformat.format(nowDate);          //获取当前系统时间
        String path = fileDir+"/"+dateDirName+"/";
        fileWrite = new File(path + hubMac + "_" + dataNowString + ".bin");
        try {
            // 如果文件夹不存在，则创建
            File fileParent = fileWrite.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            fos = new FileOutputStream(fileWrite.getPath());
        } catch (FileNotFoundException e) {
            fos = null;
            Log.e(TAG, e.toString());
        }
    }

    /**
     * 防止日志频繁打印
     */
    private boolean saveDateLogFlag = false;
    public void saveData(byte[] data, int nLen) {
        if (fos != null && nLen > 0 && nLen <= data.length) {
            try {
                saveDateLogFlag = false;
                fos.write(data, 0, nLen);
            } catch (IOException e) {
                if (!saveDateLogFlag) {
                    Log.e(TAG, e.toString());
                }
                e.printStackTrace();
                saveDateLogFlag = true;
            }
        }
    }

    /**
     * 文件关闭
     */
    public void close() {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                Log.e(TAG, e.toString());
                e.printStackTrace();
            }
            fileWrite = null;
        }
    }

    @Override
    public String toString() {
        return "HexSaveData2File{" +
                "hubMac='" + hubMac + '\'' +
                ", fileDir='" + fileDir + '\'' +
                '}';
    }
}
